package com.example.music_project.service;

import com.example.music_project.mapper.UserMapper;
import com.example.music_project.tools.Constant;
import com.example.music_project.tools.JWTUtils;
import com.example.music_project.tools.Result;
import com.example.music_project.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ConcurrencyThrottleSupport;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;
    //登录查询
    public Result<Object> queryUser(String userName, String password, HttpServletRequest request) {
        Result<Object> result = new Result<>();
        //1.校验参数
        if(!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
           return result.fail("用户或密码为空");

        }
        //2.检查是否有该用户
        User user = new User(userName, password);
        User getUser = userMapper.userLogin(user);
        log.info("查询用户结果:{}", getUser);
        //校验
        if(getUser == null || getUser.getId() < 1) {
            log.error("用户不存在");
           return result.fail("用户不存在");

        }
        //校验密码
//        boolean matches = bCryptPasswordEncoder.matches(password, getUser.getPassword());
//        if(!matches) {
//            return result.fail("密码错误");
//        }
        if(!password.equals(getUser.getPassword())) {
            log.error("密码错误");
            return result.fail("密码错误");
        }
        //设置session
        request.getSession().setAttribute(Constant.USER_SESSION, getUser);
        return result.success();
        //获取token
//        Map<String, Object> map = new HashMap<>();
//        map.put(Constant.USER_ID, getUser.getId());
//        map.put(Constant.USER_USERNAME, getUser.getUserName());
//        String token = JWTUtils.getToken(map);
//        System.out.println("已经存储token：" + token);
//        return result.success(token);
    }

    public boolean register(String userName, String password) {
        if(!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            log.error("用户名或密码为空");
            return false;
        }
        // 2.加密
        String encode = bCryptPasswordEncoder.encode(password);
        // 3.存入数据库
        Integer integer = userMapper.insertUser(userName, password);
        log.info("完成插入:{}", integer);
        return true;
    }
}
